package com.anjiplus.template.gaea.business.modules.quartzReport.controller;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.anjiplus.template.gaea.business.modules.quartz.controller.QuartzTaskController;
import com.anjiplus.template.gaea.business.modules.quartz.mode.QuartzForm;
import com.anjiplus.template.gaea.business.modules.quartz.util.Result;
import com.anjiplus.template.gaea.business.modules.tbscheduledgaeareport.dao.CompanyTaskMapper;
import com.anjiplus.template.gaea.business.modules.tbscheduledgaeareport.entity.CompanyTask;
import com.anjiplus.template.gaea.business.modules.tbscheduledgaeareport.form.TBScheduledGaeaReportForm;
import com.anjiplus.template.gaea.business.modules.tbscheduledgaeareport.service.TBScheduledGaeaReportService;
import com.anjiplus.template.gaea.business.modules.tbscheduledgaeareport.vo.TBScheduledGaeaReportVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.example.quartz.service.UtilService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/quartzReport")
public class quartzReportController {

    @Autowired
    private TBScheduledGaeaReportService tBScheduledGaeaReportService;
    @Autowired
    private QuartzTaskController quartzTaskController;

    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    private CompanyTaskMapper companyTaskMapper;

    @Autowired
    private UtilService utilService;

    /**
     * 添加启动任务定时任务
     *
     * @param param
     * @return
     */
    @PostMapping("/addOrupdatescheduledTask")
    public Result addscheduledTask(@RequestBody QuartzForm param) {

        param.setCronExpression(param.getScheduledCode());
        // 查询任务类
        if (ObjectUtils.isEmpty(param.getTaskInfoId())) {
            //查询任务类
            List<Map<String, Object>> list = jdbcTemplate.queryForList("select  * from " + utilService.getGSYY() + ".\"timed_reference_class\" where \"status\" =0 ");
            if (ObjectUtils.isEmpty(list)) {
                return Result.fail("可分配的定时任务类已经满了,请删除无用的定时任务释放定时类！！！");
            }
            String UUID = IdUtil.simpleUUID();
            String referencePath = list.get(0).get("reference_path").toString();
            jdbcTemplate.update("  INSERT INTO " + utilService.getGSYY() + ".\"task_info\" ( \"id\",\"task_class\", \"task_desc\", \"delete_state\") " +
                    "VALUES ('" + UUID + "', '" + referencePath + "', NULL, 0)");
            param.setTaskInfoId(UUID);
            //修改任务类
            jdbcTemplate.update("update " + utilService.getGSYY() + ".\"timed_reference_class\" set \"status\" = 1 where \"reference_path\" ='" + referencePath + "'");
        }
        String scheduledCode = param.getScheduledCode();
        if (StringUtils.isEmpty(param.getId())) {
            param.setType(1);
            JSONObject jsonObject = quartzTaskController.addTask(param);
            String data = jsonObject.getString("data");
//            Object data = result.getData();
            TBScheduledGaeaReportForm tbScheduledGaeaReportForm = new TBScheduledGaeaReportForm();
            // 改为datasource的code
            tbScheduledGaeaReportForm.setGaeaReportCode(param.getGaeaReportCode());
            tbScheduledGaeaReportForm.setScheduledCode(data.toString());
            tbScheduledGaeaReportForm.setEnableStatus(param.getEnableStatus());
            tbScheduledGaeaReportForm.setGaeaReportName(param.getGaeaReportName());
            tbScheduledGaeaReportForm.setScheduledName(param.getScheduledName());
            tbScheduledGaeaReportForm.setScheduledExpression(scheduledCode);
            tbScheduledGaeaReportForm.setTaskInfoId(param.getTaskInfoId());
            tBScheduledGaeaReportService.save(tbScheduledGaeaReportForm);
            return Result.success("添加成功");
        } else {
            param.setType(1);
            TBScheduledGaeaReportVO tbScheduledGaeaReportVO = tBScheduledGaeaReportService.selectById(String.valueOf(param.getId()));
            LambdaQueryWrapper<CompanyTask> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CompanyTask::getTaskGroup, tbScheduledGaeaReportVO.getScheduledCode());
            CompanyTask companyTask = companyTaskMapper.selectOne(wrapper);

            param.setCompanyTaskId(companyTask.getId());
            JSONObject result = quartzTaskController.updateTask(param);
            TBScheduledGaeaReportForm tbScheduledGaeaReportForm = new TBScheduledGaeaReportForm();
            // 改为datasource的code
            tbScheduledGaeaReportForm.setGaeaReportCode(param.getGaeaReportCode());
            tbScheduledGaeaReportForm.setId(param.getId());
            tbScheduledGaeaReportForm.setEnableStatus(param.getEnableStatus());
            tbScheduledGaeaReportForm.setGaeaReportName(param.getGaeaReportName());
            tbScheduledGaeaReportForm.setScheduledName(param.getScheduledName());
            tbScheduledGaeaReportForm.setScheduledExpression(scheduledCode);
            tBScheduledGaeaReportService.updateById(tbScheduledGaeaReportForm);
            return Result.success("修改成功");
        }
    }

    /**
     * 插入数据并返记录的主键ID
     *
     * @param jdbcTemplate
     * @param sql
     * @return
     */
    public static String updateID(JdbcTemplate jdbcTemplate, String sql, String idname) {
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
                // new String[]{"ID"} 确定主键名称
                PreparedStatement ps = conn.prepareStatement(sql, new String[]{idname});
                return ps;
            }
        }, keyHolder);
        return keyHolder.getKey().toString();
    }

}
